import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { useUserStore } from '../stores/userStore'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue')
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/RegisterView.vue')
    },
    {
      path: '/article/:id',
      name: 'article',
      component: () => import('../views/ArticleView.vue'),
      props: true // 允许将路由参数作为组件的 props
    },
    {
      path: '/user/:id',
      name: 'userProfile',
      component: () => import('../views/UserProfileView.vue'),
      props: true,
      meta: { requiresAuth: true }, // 需要登录才能访问
      beforeRouteUpdate(to, from, next) {
        // 当路由参数改变时，强制重新渲染组件
        if (to.params.id !== from.params.id) {
          to.meta.reload = true
        }
        next()
      }
    }
  ],
  scrollBehavior(to, from, savedPosition) {
    if (to.meta.reload) {
      to.meta.reload = false
      return { left: 0, top: 0 }
    }
    return savedPosition
  }
})

// 导航守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  
  // 检查路由是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 直接使用 store 中的登录状态
    if (!userStore.isLogin) {
      // 显示提示信息
      if (confirm('该页面需要登录后才能访问，是否前往登录？')) {
        // 如果未登录，重定向到登录页面
        next({
          path: '/login',
          query: { redirect: to.fullPath }
        })
      } else {
        next(false)
      }
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
